package com.atguigu.juc.homework1;



import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Number1{
    private int number = 0;
  private   Lock lock = new ReentrantLock();
  private   Condition condition=lock.newCondition();
    public void add() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while (number != 0) {

                condition.await();
            }

                    //2.干活
                    System.out.println(Thread.currentThread().getName() + "---" + (number++));
                    //3.通知
                    condition.signalAll();
            } finally {
                    //3.通知
                    lock.unlock();
                }
        }

            public void sub () throws InterruptedException {
                lock.lock();
                try {
                    //1.判断
                    while (number == 0) {

                        condition.await();
                    }

                            //2.干活
                            System.out.println(Thread.currentThread().getName() + "---" + (number--));
                            //3.通知
                            condition.signalAll();
                        } finally {
                            lock.unlock();
                        }
                    }
                }



/**
 *
 有一个初始值为零的变量，现有两个线程对该变量操作，实现一个线程对变量加1，实现一个线程对变量减1,交替来10轮
 1.线程    操作     资源类
 2.判断   干活    通知
 3.防止虚假传唤用while条件
 */
public class ThreadCommunicationChange {
    public static void main(String[] args) {
        Number1 number = new Number1();
        new Thread(() -> { for (int i = 0; i <10 ; i++) {
            try {
                number.add();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"A").start();

        new Thread(() -> { for (int i = 0; i <10 ; i++) {
            try {
                number.sub();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"B").start();

        new Thread(() -> { for (int i = 0; i <10 ; i++) {
            try {
                number.add();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"C").start();

        new Thread(() -> { for (int i = 0; i <10 ; i++) {
            try {
                number.sub();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"D").start();
    }
}
